<script setup lang="jsx">

import {useRoute} from "vue-router";
import {computed, onMounted, reactive, ref, onBeforeMount} from "vue";
import {useUserStore} from "@/stores/user.js";
import router from "@/router/index.js";
import {getCommentCount, listUserPageActivity, oneActivity, pageAllGrade} from "@/api/activity.js";
import {MessagePlugin} from "tdesign-vue-next";
import {AddIcon, ChatIcon, CloudUploadIcon, SearchIcon, ShareIcon, ThumbUpIcon} from "tdesign-icons-vue-next";
import {createActivity, listActivityAdministrator} from "@/api/administrator.js";
import {createGroup, joinGroupApi, listPageGroup, listPageGroupMain} from "@/api/group.js";

const route = useRoute();
const activityId = ref()
const activityName = ref()
const activityData = reactive({
  id: 1,
  activityName: "",
  description: "",
  maxNum: 5,
  expirationTime: "",
  applicant: 1,
  grade: -1,
  type: "",
  reviewer: 9,
  activityStatus: 1,
  university: ""
});

// 活动详情 ----------------------------------------------------
const activityDetailVisible = ref(false)
const activityDetail = async () => {
  activityDetailVisible.value = true

}

// 活动id -----------------------------------------------------
onBeforeMount(async () => {
  activityId.value = route.query.activityId;
  activityName.value = route.query.activityName;
  groupCreate.activityId = route.query.activityId;

  const res1 = await oneActivity(userStore, activityId.value)
  const res = res1.data

  activityData.id = res.data.id
  activityData.activityName = res.data.activityName
  activityData.description = res.data.description
  activityData.maxNum = res.data.maxNum
  activityData.expirationTime = res.data.expirationTime
  activityData.applicant = res.data.applicant
  activityData.grade = res.data.grade
  activityData.type = res.data.type
  activityData.reviewer = res.data.reviewer
  activityData.activityStatus = res.data.activityStatus
  activityData.university = res.data.university

})

const userStore = useUserStore()

// 团队卡片 --------------------------------------------------------------------

const cover = 'https://tdesign.gtimg.com/site/source/card-demo.png';

const ellipsisState1 = {
  row: 2,
  expandable: true,
  collapsible: true,
};

// 搜索 --------------------------------------------------------------------------

const searchValue = ref('');
const onClear = () => {
  console.log('clear');
};
const onBlur = () => {
  console.log('blur');
};

// 数据 -----------------------------------------------------------------------------------------------
const groupList = ref([])
onMounted(async () => {
  const res = await listPageGroupMain(userStore, current.value, pageSize.value, '', '', '', '', 0, '', '', '', activityId.value, '', '')
  if (res.data.code === 40000) {
    await MessagePlugin.error("活动已过期或不存在")
  } else {
    groupList.value = res.data.data.records
    total.value = res.data.data.total
  }
})


// 创建团队 ---------------------------------------------------------------------------------
const createForm = ref(null);
const groupCreate = reactive({
  description: '',
  address: '',
  expirationTime: ref(formatDate(new Date())),
  neededNum: 2,
  contactInfo: '',
  activityId: activityId.value,
  startTime: ref(formatDate(new Date())),
  endTime: ref(formatDate(new Date())),

});



const rules = computed(()=> ({
      description: [
        {required: false, message: '选填', type: 'error'},
      ],
      address: [
        {required: false, message: '选填', type: 'error'},
      ],
      neededNum: [
        {required: true, message: '人数必填，且最少两人', type: 'error'},
        {number: true, message: '请输入数字', type: 'warning'},
        {max: activityData.maxNum, message: '超过该活动允许的最大人数', type: 'error'}
      ],
      contactInfo: [
        {required: true, message: '必填', type: 'error'},
      ],
    }))
;

const createVisible = ref(false);
const createClose = () => {
  createVisible.value = false
}

const createWindow = () => {
  createVisible.value = true
}

const onSubmitCreate = async () => {
  const res = await createGroup(userStore, groupCreate.description, groupCreate.address, groupCreate.expirationTime, groupCreate.neededNum, groupCreate.contactInfo, groupCreate.activityId, groupCreate.startTime, groupCreate.endTime);
  if (res.data.code !== 0) {
    await MessagePlugin.error("创建失败" + res.data.description)
  } else {
    createVisible.value = false
    await MessagePlugin.success("创建成功")
  }

}

const handleClear = () => {
  createForm.value.clearValidate();
};

const onReset = () => {
  MessagePlugin.success('重置成功');
};

const error = ref(undefined);
const tips = computed(() => {
  if (error.value === 'exceed-maximum') return 'number can not be exceed maximum';
  if (error.value === 'below-minimum') {
    groupCreate.neededNum = 2
    return '最少为两人';
  }
  return undefined;
});

const onValidate = (p) => {
  error.value = p.error;
};
// 分页控件 ---------------------------------------------------------------------------------------------
const current = ref(1);
const pageSize = ref(6);
const total = ref(0)

const pageSizeOption = [6, 12, 24]

const onPageSizeChange = async (size) => {
  const res = await listPageGroupMain(userStore, current.value, pageSize.value, '', '', '', '', 0, '', '', '', activityId.value, '', '')
  groupList.value = res.data.data.records
  total.value = res.data.data.total
};

const onCurrentChange = async (index, pageInfo) => {
  const res = await listPageGroupMain(userStore, current.value, pageSize.value, '', '', '', '', 0, '', '', '', activityId.value, '', '')
  groupList.value = res.data.data.records
  total.value = res.data.data.total
};

const onChange = (pageInfo) => {
  console.log(pageInfo);
};

// 当前的时间 -------------------------------------------------------------
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const clickHandler = () => {
  MessagePlugin.success('操作');
};

function renderPopupContent(item) {
  return (
      <div>
        <t-divider align="left">描述</t-divider>
        <div>{item.description}</div>
        <t-divider align="left">地点</t-divider>
        <div>{item.address}</div>
        <t-divider align="left">联系方式</t-divider>
        <div>{item.contactInfo}</div>
      </div>
  )
}

// 确认加入 ---------------------------------------
const joinConfirm = async (item) => {
  const res = await joinGroupApi(userStore, item.id)
  if (res.data.data !== true) {
    await MessagePlugin.error("加入失败: " + res.data.description)
  } else {
    await MessagePlugin.success("加入成功")
    const res = await listPageGroupMain(userStore, current.value, pageSize.value, '', '', '', '', 0, '', '', '', activityId.value, '', '')
    groupList.value = res.data.data.records
    total.value = res.data.data.total

  }
}

// 分享活动 ------------------------------------------------------
const shareActivity = async () => {
  try {
    const currentUrl = window.location.href; // 获取完整 URL
    await navigator.clipboard.writeText(currentUrl);
    await MessagePlugin.success('活动链接已复制到剪贴板！');
  } catch (err) {
    console.error('复制失败:', err);
    await MessagePlugin.error('复制失败，请手动复制链接');
  }
}

// 活动评论 ------------------------------------------------------
const commentVisible = ref(false)
const commentList = ref([])
// 默认为1，current用来做锚点
const commentCurrent = ref(1)
const commentTotal = ref(0)
const commentPageSize = ref(6) // 单次加载数量
const commentCount = ref(0) // 首页评论数量

onMounted(async () => {
  const res = await getCommentCount(userStore, activityId.value);
  commentCount.value = res.data.data
})


const commentWindow = async () => {
  commentVisible.value = true
  if (commentList.value.length === 0) {
    const res = await pageAllGrade(userStore, commentCurrent.value, commentPageSize.value, activityId.value);
    commentTotal.value = res.data.data.total
    commentList.value = res.data.data.records
  }
}

const asyncLoadingRadio = ref('load-more');

const loadMore = async () => {
  asyncLoadingRadio.value = 'loading';
  const res = await pageAllGrade(userStore, ++commentCurrent.value, commentPageSize.value, activityId.value);
  commentTotal.value = res.data.data.total
  commentList.value.push(...res.data.data.records)
  if (commentList.value.length === commentTotal.value) {
    asyncLoadingRadio.value = 'loading-custom'
  } else {
    asyncLoadingRadio.value = 'load-more';
  }
};

const asyncLoading = computed(() => {
  if (asyncLoadingRadio.value === 'loading-custom') {
    return '没有更多数据了';
  }
  return asyncLoadingRadio.value;
});
const imageUrl = 'https://tdesign.gtimg.com/site/avatar.jpg';

</script>

<template>
  <t-layout style="
      height: 100%;                /* 继承父容器高度 */
    ">
    <t-header style="display: flex;               /* 启用flex布局 */
      align-items: center;         /* 垂直居中 */
      justify-content: center;     /* 水平居中 */
      padding-left: 2%;
      padding-right: 1%;
      background-color: #e5e5e5;
      width: auto;">
      <!--      <div style="display: flex; justify-content: flex-start; width: 100%">-->
      <!--        <t-radio-group style="background-color: #cccccc" variant="primary-filled" default-value="1">-->
      <!--          <t-radio-button value="1">已通过</t-radio-button>-->
      <!--          <t-radio-button value="0">未审核</t-radio-button>-->
      <!--          <t-radio-button value="2">已拒绝</t-radio-button>-->
      <!--        </t-radio-group>-->
      <!--      </div>-->
      <div style="display: flex; justify-content: flex-end; width: 100% ">
        <!--        <div style="padding-right: 2%">-->
        <!--          <t-input v-model="searchValue" placeholder="输入活动" borderless clearable @clear="onClear"-->
        <!--                   @blur="onBlur"></t-input>-->
        <!--        </div>-->
        <!--        <div style="padding-right: 2%">-->
        <!--          <t-button shape="circle" theme="primary">-->
        <!--            <template #icon>-->
        <!--              <SearchIcon/>-->
        <!--            </template>-->
        <!--          </t-button>-->
        <!--        </div>-->
        <div>
          <t-button shape="rectangle" theme="primary" @click="createWindow">
            <template #icon>
              <AddIcon/>
            </template>
            创建团队
          </t-button>
        </div>
      </div>


    </t-header>
    <t-content style="background-color: white; width: 100%; ">
      <div style="display: flex; align-items: center; ">
        <div style="display: flex; align-items: center;">
          <h2 style="padding-left: 20px; padding-top: 15px">
            {{ activityName }}
          </h2>
          <div style="padding-left: 10px; padding-top: 20px">
            <t-button theme="default" @click="activityDetail">
              详情
            </t-button>
          </div>
          <div style="padding-left: 10px; padding-top: 20px">
            <t-popup content="分享活动" trigger="hover">
              <t-button theme="default" shape="circle" @click="shareActivity">
                <template #icon>
                  <ShareIcon/>
                </template>
              </t-button>
            </t-popup>

          </div>
        </div>
        <div style="display: flex; align-items: center; margin-left: auto;">
          <div style="padding-left: 10px; padding-top: 20px; padding-right: 20px; display: flex">
            <t-rate disabled :value="activityData.grade" style="padding-right: 20px"/>
            <h3 v-if="activityData.grade === null">暂无评分</h3>
            <h3 v-if="activityData.grade !== null && activityData.grade <= 1">差评如潮</h3>
            <h3 v-if="activityData.grade > 1 && activityData.grade <= 2">多半差评</h3>
            <h3 v-if="activityData.grade > 2 && activityData.grade <= 3">褒贬不一</h3>
            <h3 v-if="activityData.grade > 3 && activityData.grade <= 4">多半好评</h3>
            <h3 v-if="activityData.grade > 4">好评如潮</h3>
          </div>
          <div style="padding-left: 10px; padding-top: 20px; padding-right: 20px">
            <t-button theme="default" @click="commentWindow">
              评价({{commentCount}})
            </t-button>
          </div>
        </div>
      </div>

      <t-divider style="padding-left: 20px"/>

      <div v-if="groupList.length !== 0" style="
        display: grid;
        grid-template-columns: repeat(auto-fill, 360px);
        justify-content: center;
        gap: 16px;
        padding-top: 2%;

  ">
        <div v-for="(item, index) in groupList">
          <t-card :title="`团队${item.id}`" header-bordered hover-shadow :style="{ width: '360px' }">

            <div>截止时间: {{ item.expirationTime }}</div>
            <div>开始时间: {{ item.startTime }}</div>
            <div>结束时间: {{ item.endTime }}</div>
            <div>拼团情况: {{ item.alreadyNum }}/{{ item.neededNum }}</div>

            <div style="display: flex; justify-content: flex-end; width: 100% ">
              <div style="padding-right: 2%">
                <t-popup placement="bottom" :content="renderPopupContent(item)" :overlay-style="{ width: '460px' }">
                  <t-button shape="rectangle">
                    详情
                  </t-button>
                </t-popup>

              </div>

              <div style="padding-right: 2%">
                <t-popconfirm content="是否要加入" placement="bottom" @confirm="joinConfirm(item)">
                  <t-button variant="outline">加入</t-button>
                </t-popconfirm>
              </div>
            </div>

          </t-card>
        </div>
      </div>
      <t-space v-else direction="vertical" align="center" style="width: 100%;  padding-top: 10%">
        <t-empty title="暂无团队，点击右上角创建一个吧"/>
      </t-space>

      <div style="padding-left: 2%; padding-right: 2%; padding-top: 2%">
        <t-pagination
            v-model="current"
            v-model:pageSize="pageSize"
            :total=total
            @change="onChange"
            @page-size-change="onPageSizeChange"
            @current-change="onCurrentChange"
            :pageSizeOptions="pageSizeOption"
        />
      </div>
    </t-content>

    <t-dialog placement="center" header="创建团队" :footer="false" :visible="createVisible" :on-confirm="createClose"
              :on-close="createClose"
              width="50%">
      <t-divider/>
      <t-form ref="createForm" :data="groupCreate" :rules="rules" @reset="onReset" @submit="onSubmitCreate">
        <t-form-item label="活动描述" help="" name="description">
          <t-textarea
              placeholder="描述一下团队，例如运动相关的话可以描述一下自己的技术"
              v-model="groupCreate.description"
              name="description"
              :autosize="true"
              :maxcharacter="100"
          />
        </t-form-item>
        <t-form-item label="活动地点" help="" name="address">
          <t-textarea
              placeholder="地点清晰可以让人更乐意加入团队"
              v-model="groupCreate.address"
              name="description"
              :autosize="true"
              :maxcharacter="64"
          />
        </t-form-item>


        <t-form-item
            label="截止时间"
            name="expirationTime"
            :rules="[
        { required: true, message: '此项必填' },
      ]"
        >
          <t-date-picker v-model="groupCreate.expirationTime" enable-time-picker clearable/>
        </t-form-item>

        <t-form-item label="需要人数" name="neededNum" help="人数至少要两人">
          <t-input-number
              :min="2"
              :max="activityData.maxNum"
              @validate="onValidate"
              :tips="tips"
              v-model="groupCreate.neededNum"
          />
        </t-form-item>

        <t-form-item label="联系方式" help="" name="contactInfo">
          <t-textarea
              placeholder="联系方式，例如：“qq: 177xxxxxx”、“手机：135xxxxxxx”"
              v-model="groupCreate.contactInfo"
              name="description"
              :autosize="true"
              :maxcharacter="64"
          />
        </t-form-item>

        <t-form-item
            label="开始时间"
            name="startTime"
            :rules="[
        { required: true, message: '此项必填' },
      ]"
        >
          <t-date-picker v-model="groupCreate.startTime" enable-time-picker clearable/>
        </t-form-item>

        <t-form-item
            label="结束时间"
            name="endTime"
            :rules="[
        { required: true, message: '此项必填' },
      ]"
        >
          <t-date-picker v-model="groupCreate.endTime" enable-time-picker clearable/>
        </t-form-item>

        <t-form-item>
          <t-space size="small">
            <t-button theme="primary" type="submit">提交</t-button>
            <t-button theme="default" variant="base" type="reset">重置</t-button>
            <t-button theme="default" variant="base" @click="handleClear">清空校验结果</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>


    <t-dialog
        closeBtn
        closeOnOverlayClick
        closeOnEscKeydown
        :footer="false"
        v-model:visible="activityDetailVisible"
    >
      <div>活动名：{{ activityData.activityName }}</div>
      <div>活动类别：{{ activityData.type }}</div>
      <div>活动描述：{{ activityData.description }}</div>
      <div>最大人数：{{ activityData.maxNum }}</div>
      <div>活动常驻截止时间：{{ activityData.expirationTime }}</div>
      <!--      <p>{{activityData.activityName}}</p>-->
    </t-dialog>

    <!--    评论列表-->
    <t-dialog
        width="40%"
        closeBtn
        closeOnOverlayClick
        closeOnEscKeydown
        :footer="false"
        v-model:visible="commentVisible">
      <t-list style="height: 400px" :async-loading="asyncLoading" split @load-more="loadMore" >
        <t-list-item v-for="(item, index) in commentList" :key="index">
          <t-list-item-meta :image="imageUrl" :title="item.userId" :description="item.comment"/>
        </t-list-item>
      </t-list>
    </t-dialog>
  </t-layout>

</template>

<style scoped>
.text-container {
  word-wrap: break-word; /* 支持长单词和 URL 的换行 */
  white-space: normal; /* 允许文本换行 */
  overflow-wrap: break-word; /* 另一种支持换行的方式 */
}


</style>